package com.hksj.ecm.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.base.service.DefaultDeviceService;
import com.hksj.cbm.service.DeviceInstanceService;
import com.hksj.cbm.util.CellStyleStrategy;
import com.hksj.cbm.util.CustomCellWriteHandler;
import com.hksj.cbm.util.DateTimeFormatUtil;
import com.hksj.cbm.util.PageListUtils;
import com.hksj.cbm.vo.SpaceModelVO;
import com.hksj.ecm.dto.EnergyDeviceDTO;
import com.hksj.ecm.dto.EnergyHistoryDeviceDTO;
import com.hksj.ecm.mapper.EnergyDeviceMapper;
import com.hksj.ecm.vo.EnergyDeviceVO;
import com.hksj.ecm.vo.EnergyHistoryDeviceVO;
import com.hksj.ecm.vo.ExportEnergyHistoryVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class EnergyDeviceService {

    private static final Logger log = LoggerFactory.getLogger(EnergyDeviceService.class);

    @Autowired
    private EnergyDeviceMapper energyDeviceMapper;

    @Autowired
    private DeviceInstanceService deviceInstanceService;

    @Autowired
    private DefaultDeviceService defaultDeviceService;

    /**
     * 根据页码查询能源设备信息
     *
     * @param dto 查询条件封装对象
     * @return 包含查询结果的分页对象
     */
    public Page<EnergyDeviceVO> queryEnergyDeviceByPage(EnergyDeviceDTO dto) {
        // 初始化分页对象，设置当前页码和每页显示数量
        Page<EnergyDeviceVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        // 调用mapper查询分页数据
        List<EnergyDeviceVO> list = energyDeviceMapper.queryEnergyDeviceByPage(dto,page);
        // 如果查询结果为空，直接返回空的分页对象
        if (CollectionUtils.isEmpty(list)){
            return page;
        }
        // 从查询结果中提取非空路径信息
        List<String> pathList = list.stream()
                .map(EnergyDeviceVO::getPaths)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 将路径信息转换为UTF8格式
        Map<String, List<SpaceModelVO>> pathNameMap = deviceInstanceService.devicePathConvertToUTF8(pathList);
        // 如果路径信息非空，则将转换后的路径名称关联到查询结果中
        if (CollUtil.isNotEmpty(pathNameMap)) {
            list.forEach(vo -> {
                List<SpaceModelVO> spaceModelVOList = pathNameMap.get(vo.getPaths());
                if (StringUtils.isNotBlank(dto.getPaths()) && CollUtil.isNotEmpty(spaceModelVOList)){
                    spaceModelVOList = spaceModelVOList.stream().filter(spaceModelVO -> !dto.getPaths().contains(spaceModelVO.getId().toString())).collect(Collectors.toList());
                }
                vo.setSpaceModelVOList(spaceModelVOList);
            });
        }
        // 设置分页对象的查询结果记录
        page.setRecords(list);
        // 返回包含查询结果的分页对象
        return page;
    }


    public Page<EnergyHistoryDeviceVO> queryEnergyHistoryDevice(EnergyHistoryDeviceDTO dto) {
        // 用于存储时间列表
        List<String> timeList = new ArrayList<>();

        // 根据周期类型生成相应的时间列表
        if (ObjectUtil.equals(dto.getCycleType(), "1")) {
            // 小时周期
            timeList = DateTimeFormatUtil.getHourList(dto.getStartTime(), dto.getEndTime());
        } else if (ObjectUtil.equals(dto.getCycleType(), "2")) {
            // 天周期
            timeList = DateTimeFormatUtil.getDayList(dto.getStartTime(), dto.getEndTime());
        }
        // 初始化查询结果列表
        List<EnergyHistoryDeviceVO> energyHistoryList = timeList.stream().map(time -> {
                    EnergyHistoryDeviceVO energyHistoryDeviceVO = new EnergyHistoryDeviceVO();
                    energyHistoryDeviceVO.setCountTime(time);
                    return energyHistoryDeviceVO;
                })
                .collect(Collectors.toList());

        // 如果查询结果为空，直接返回空的分页对象
        if (CollectionUtils.isEmpty(energyHistoryList)){
            return new Page<>();
        }

        String tableName = "";
        //设备对应的超级表产品id和设备id实现对应
        try {
            tableName = defaultDeviceService.getTableName(dto.getProductId());
            List<EnergyHistoryDeviceVO> data = energyDeviceMapper.queryEnergyHistoryDevice(tableName, dto);
            if (!CollectionUtils.isEmpty(data)){
                data.forEach(vo -> {
                    vo.setCountTime(vo.getCountTime().replace("T", " "));
                    vo.setCountTime(vo.getCountTime() + ":00:00");
                });
                Map<String, EnergyHistoryDeviceVO> map = data.stream().collect(Collectors.toMap(EnergyHistoryDeviceVO::getCountTime, item -> item));
                energyHistoryList.forEach(vo -> {
                    if (map.containsKey(vo.getCountTime())) {
                        EnergyHistoryDeviceVO val = map.get(vo.getCountTime());
                        vo.setConsumption(Math.round(val.getConsumption() * 100.0) / 100.0);
                    }

                });
            }
        } catch (Exception e) {
            log.error("Error querying table {}: {}", tableName, e.getMessage(), e);
        }
        // 设置分页(内存分页)
        Page<EnergyHistoryDeviceVO> page=PageListUtils.getPages(Math.toIntExact(dto.getPageNum()),Math.toIntExact(dto.getPageSize()) , energyHistoryList);
        //返回
        return page;
    }

    public void exportEnergyHistoryDeviceInfo(EnergyHistoryDeviceDTO dto, HttpServletResponse response) throws Exception {
        List<EnergyHistoryDeviceVO> finalEnergyHistoryList = queryEnergyHistoryDevice(dto).getRecords();
        List<ExportEnergyHistoryVO> data = IntStream.range(0, finalEnergyHistoryList.size())
                .mapToObj(index -> {
                    EnergyHistoryDeviceVO energyHistory = finalEnergyHistoryList.get(index);
                    ExportEnergyHistoryVO vo = new ExportEnergyHistoryVO();
                    vo.setSeq(index + 1);
                    vo.setConsumption(energyHistory.getConsumption());
                    vo.setCountTime(energyHistory.getCountTime().replace("T", " "));
                    return vo;
                })
                .collect(Collectors.toList());

        List<List<String>> header= new ArrayList<>();
        header.add(Collections.singletonList("序号"));
        String headerText = getHeaderText(dto.getCycleType(), dto.getCountType());
        header.add(Collections.singletonList(headerText));
        header.add(Collections.singletonList("统计时间"));

        String fileName = new StringBuffer()
                .append("设备历史数据表")
                .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date()))
                .append(".xlsx")
                .toString();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        EasyExcel.write(response.getOutputStream(), ExportEnergyHistoryVO.class)
                .registerWriteHandler(new CellStyleStrategy(Collections.singletonList(0),new WriteCellStyle(), new WriteCellStyle()))
                .head(header)
                .sheet("sheet1")
                .doWrite(data);
    }

    private String getHeaderText(String cycleType, String countType) {
        if ("Leijdl".equals(countType)) {
            return "每" + (cycleType.equals("1") ? "小时" : "天") + "功耗kw";
        } else {
            return "每" + (cycleType.equals("1") ? "小时" : "天") + "用量（立方米）";
        }
    }

}
